package com.blockmeta.bbs.immodule.fragment;


import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseLazyFragment;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.CircleDetailActivity;
import com.blockmeta.bbs.immodule.activity.chat.UCGChatActivity;
import com.blockmeta.bbs.immodule.adapter.ContactsCircleAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.ICircleEntry;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.Impl.CircleDomainService;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.net.api.RecommendCircleApi;
import com.blockmeta.bbs.immodule.net.pojo.IMCircleEntityBook;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.subscribers.ResourceSubscriber;

import static com.blockmeta.bbs.immodule.Constants.CANCHOOSE;
import static com.blockmeta.bbs.immodule.Constants.CHOOSESINGLE;


/**
 * @author airthor
 * @date 2019/3/4
 * A simple {@link Fragment} subclass.
 * 加入的圈子
 */
public class CirclesFragment extends BaseLazyFragment {

    @BindView(R2.id.rcv_circle_list)
    RecyclerView mRcvCircleList;

    public ContactsCircleAdapter mCircleAdapter;

    private List<ICircleEntry> mICircleEntries = new ArrayList<>();
    private boolean mCanChoose;
    private boolean mChooseSingle;
    private List<IMCircleEntityBook> recommandCircles;

    public static CirclesFragment newInstance(boolean canChoose, boolean chooseSingle) {
        CirclesFragment f = new CirclesFragment();
        f.setArguments(buildArgs(canChoose, chooseSingle));
        return f;
    }

    public static Bundle buildArgs(final boolean canChoose, boolean chooseSingle) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(CANCHOOSE, canChoose);
        bundle.putBoolean(CHOOSESINGLE, chooseSingle);
        return bundle;
    }

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_circles, container, false);
    }

    @Override
    protected void initializeLayout() {
        IMApplicationContext.getIMMetaService().register(this);
        EventBus.getDefault().register(this);
        mCanChoose = getArguments().getBoolean(CANCHOOSE);
        mChooseSingle = getArguments().getBoolean(CHOOSESINGLE);
        //热门圈子是通过Https请求过来的，单独做处理，但是不计入数据库！
        mRcvCircleList.setLayoutManager(new LinearLayoutManager(mContext));
        ((SimpleItemAnimator) mRcvCircleList.getItemAnimator()).setSupportsChangeAnimations(false);
        mCircleAdapter = new ContactsCircleAdapter(R.layout.item_join_circle_list_hot, mICircleEntries);
        mCircleAdapter.bindToRecyclerView(mRcvCircleList);
        mCircleAdapter.setEditable(mCanChoose, mChooseSingle);
        //加入按钮点击
        mCircleAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() != R.id.btn_join) {
                    return;
                }
                joinCircle(mICircleEntries.get(position).getId(), mICircleEntries.get(position).getCircleAuthRule()
                        , mICircleEntries.get(position).getUserLevel(), position);
            }
        });
        //条目点击
        mCircleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (mCanChoose) {
                    mCircleAdapter.checkChange(position);
                } else {
                    boolean joinState = mICircleEntries.get(position).getJoinState();
                    long circleId = mICircleEntries.get(position).getId();
                    //根据加入状态跳转不同界面。已加入的跳转聊天页面；未加入的跳转圈子详情页面。
                    if (joinState) {
                        Intent intent = new Intent(mContext, UCGChatActivity.class);
                        intent.putExtra(Params.USER_TAG, circleId);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(mContext, CircleDetailActivity.class);
                        intent.putExtra(Params.CIRCLE_ID, circleId);
                        intent.putExtra(Params.JOIN_STATE, false);
                        startActivity(intent);
                    }

                }
            }
        });
    }

    @Override
    protected void netWork() {
        doNetWork();
    }


    /**
     * 加入推荐圈子
     *
     * @param circleId       圈子ID
     * @param circleAuthRule
     * @param position
     */
    private void joinCircle(final long circleId, int circleAuthRule, int userLevel, final int position) {
        IMApplicationContext.getCircleDomainService().joinCircle(mContext, circleId, circleAuthRule, userLevel, new CircleDomainService.CircleJoinCallBack() {

            @Override
            public void onSuccess(String message) {
                //本地更新加入状态
                ICircleEntry item = mCircleAdapter.getItem(position);
                item.setJoinState(true);
                mCircleAdapter.notifyItemChanged(position);
                RouterHelper.startActivity(mContext, RouterPath.IM_UCGChatActivity_ACTIVITY, String.valueOf(circleId));
            }

            @Override
            public void onFail() {

            }
        });
    }


    public synchronized void doNetWork() {
        if(!AccountHelper.isLogin()){
            return;
        }
        List<IMCircleEntityBook> dbCircleBook = getMyCircles();
        mICircleEntries.clear();
        mICircleEntries.addAll(dbCircleBook);
        mCircleAdapter.notifyDataSetChanged();
//        mICircleEntries.clear();
//        if (recommandCircles != null) {
//            List<IMCircleEntityBook> dbCircleBook = getMyCircles();
//            mICircleEntries.addAll(dbCircleBook);
//            addRecommendCircles(recommandCircles);
//            mCircleAdapter.notifyDataSetChanged();
//
//        } else if (mCanChoose) {
//            List<IMCircleEntityBook> dbCircleBook = getMyCircles();
//            mICircleEntries.addAll(dbCircleBook);
//            mCircleAdapter.notifyDataSetChanged();
//
//        } else {
//            ProgressBarUtil.showProgress(mContext);
//            RetrofitFactory.getRetrofit().create(RecommendCircleApi.class)
//                    .getHotChatGroupList(AccountHelper.getUidInt())
//                    .compose(RxUtil.<List<IMCircleEntityBook>>commonResult())
//                    .compose(RxUtil.<List<IMCircleEntityBook>>rxSchedulerHelper())
//                    .compose(((BaseActivity) mContext).<List<IMCircleEntityBook>>bindToLifecycle())
//                    .subscribe(new ResourceSubscriber<List<IMCircleEntityBook>>() {
//                        @Override
//                        public void onNext(List<IMCircleEntityBook> imCircleEntityBooks) {
//
//                            synchronized (mICircleEntries){
//                                mICircleEntries.clear();
//                                recommandCircles = imCircleEntityBooks;
//
//                                List<IMCircleEntityBook> dbCircleBook = getMyCircles();
//                                mICircleEntries.addAll(dbCircleBook);
//                                addRecommendCircles(imCircleEntityBooks);
//                            }
//                        }
//
//                        @Override
//                        public void onError(Throwable t) {
//                            ProgressBarUtil.dismissProgress(mContext);
//                            synchronized (mICircleEntries){
//                                mICircleEntries.clear();
//                                List<IMCircleEntityBook> dbCircleBook = getMyCircles();
//                                mICircleEntries.addAll(dbCircleBook);
//                            }
//                            mCircleAdapter.notifyDataSetChanged();
//                        }
//
//                        @Override
//                        public void onComplete() {
//                            ProgressBarUtil.dismissProgress(mContext);
//                            mCircleAdapter.notifyDataSetChanged();
//                        }
//                    });
//        }
    }

    private void addRecommendCircles(List<IMCircleEntityBook> recommandCircles) {
        List<IMCircleEntityBook> imCircleRecommendBooks = new ArrayList<>();
        for (IMCircleEntityBook imCircleEntityBook : recommandCircles) {
            if (!imCircleEntityBook.joinState) {
                imCircleRecommendBooks.add(imCircleEntityBook);
            }
        }
        mICircleEntries.addAll(imCircleRecommendBooks);
    }

    @NotNull
    private List<IMCircleEntityBook> getMyCircles() {
        final List<IMUserEntity> circleList = IMApplicationContext.getCircleDomainService().getGroupListMyGroupFirst(AccountHelper.getUidInt());
        List<IMCircleEntityBook> dbCircleBook = new ArrayList<>();
        for (IMUserEntity imUserEntity : circleList) {
            IMCircleEntityBook imCircleEntityBook = new IMCircleEntityBook();
            imCircleEntityBook.name = imUserEntity.getName();
            imCircleEntityBook.groupLogo = imUserEntity.getAvatarPath();
            imCircleEntityBook.grade = FormatUtil.parseInt(imUserEntity.getGroupLevel());
            imCircleEntityBook.size = imUserEntity.getGroupCount();
            imCircleEntityBook.joinState = true;
            imCircleEntityBook.recommendCircle = false;
            imCircleEntityBook.circleId = imUserEntity.getUserId();
            imCircleEntityBook.identification = imUserEntity.isIdentification() ? 1 : 0;
            imCircleEntityBook.bigClassId = imUserEntity.getCircleClass();
            imCircleEntityBook.createById = imUserEntity.getCreateUserId();
            dbCircleBook.add(imCircleEntityBook);
        }
        return dbCircleBook;
    }

    public List<ICircleEntry> getCheckedItems() {
        return mCircleAdapter.getCheckedItems();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_AddCircles event) {
        netWork();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_DeleteCircles event) {
        netWork();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_EditCircles event) {
        netWork();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_GroupList event) {
        netWork();
    }


    @Override
    public void onDestroy() {
        IMApplicationContext.getIMMetaService().unregister(this);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
